import React from 'react';
import { connect } from "react-redux";
import { homeActions} from '../../../store/home';
import { Icon } from '@blueprintjs/core';
import Menu from './Menu';
import {MenuValue} from './MenuType';

import './index.less';

class LeftMenu extends React.PureComponent {
    constructor(props) {
        super(props);
        this.init = this.init.bind(this);
        this.handleClick = this.handleClick.bind(this);
    }

    init(props) {
        const {changeMenusSelected, changeMenus, userReduce} = props;
        const {org} = userReduce;
        const menus = MenuValue[org];
        if(!menus) {
            return;
        }
        const firstMenus = menus[0];
        changeMenusSelected({menusSelected: firstMenus});
        changeMenus({menus: menus})
    }

    componentDidMount() {
        this.init(this.props);
    }

    componentWillReceiveProps(nextProps, nextContext) {
        const {homeReduce} = this.props;
        const {menusSelected, menus} = homeReduce
        if (!menusSelected.menuType || menus.length === 0) {
            this.init(nextProps);
        }
    }

    handleClick(menuType, title) {
        const {changeMenusSelected} = this.props;
        changeMenusSelected({menusSelected:{menuType, title}});
    }

    render() {
        const {userReduce, homeReduce} = this.props;
        const {role, Permission} = userReduce;
        const adminFlag = (role === "Admin");
        const edit = Permission && Permission.add === "1";
        const {menus} = homeReduce;
        return (
        <div className="LeftMenu">
            <div className="leftBar-head">
                <Icon icon={"grid-view"} iconSize={15} intent={""} />
                <span className="project-name">荔枝信息收集系统</span>
            </div>
            <div className="leftBar-mid">
                <ul className="leftBar-menu">
                    { !!menus && menus.map((menu, key)=>(
                        <Menu title={menu.title} menuType={menu.menuType} click={this.handleClick} key={key}/>
                    ))}
                    {!!adminFlag && <Menu title={"用户"} menuType={"user"} click={this.handleClick}/>}
                    {!!edit && <Menu title={"插入"} menuType={"insert"} click={this.handleClick}/>}
                </ul>
            </div>
        </div>)
    }
}

const mapStateToProps = ({ homeReduce, userReduce }) => ({ homeReduce, userReduce})
export default connect(mapStateToProps, homeActions)(LeftMenu);